package edu.wuster.blog.service.impl;

import edu.wuster.blog.entity.Message;
import edu.wuster.blog.exception.MyException;
import edu.wuster.blog.mapper.MessageMapper;
import edu.wuster.blog.mapper.UserMapper;
import edu.wuster.blog.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Message> selectByUserId(Integer userId) {
        if (userMapper.selectById(userId) == null) {
            log.info("用户不存在");
            throw new MyException("用户不存在");
        }
        return messageMapper.selectByUserId(userId);
    }

    @Override
    public void deleteById(Integer id) {
        if(messageMapper.selectById(id)==null){
            log.info("消息不存在");
            throw new MyException("消息不存在");
        }
        messageMapper.deleteById(id);
    }

    @Override
    public void addMessage(Message message) {
        if (userMapper.selectById(message.getUserId()) == null) {
            log.info("被通知用户不存在");
            throw new MyException("被通知用户不存在");
        }
        message.setCreateTime(LocalDateTime.now());
        messageMapper.addMessage(message);
    }
}
